<template>
  <div class="component-upload-media">
    <el-upload
        multiple
        :action="uploadMediaUrl"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        ref="mediaUpload"
        :headers="headers"
        :file-list="fileList"
        :show-file-list="false"
    >
    <el-button type="primary" style="margin-bottom: 10px;">点击上传</el-button>
    </el-upload>

    <!-- File List -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link @click="handleMediaCardPreview(file)" :underline="false" target="_blank">
          <span class="el-icon-document">{{ getFileName(file.name) }}</span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(file)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="预览"
        width="800px"
        append-to-body
    >
      <template v-if="isImagePreview">
        <img
            :src="dialogImageUrl"
            style="display: block; max-width: 100%; margin: 0 auto"
        />
      </template>
      <template v-else>
        <video :src="dialogImageUrl" controls style="width: 100%;"></video>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { getToken } from "@/utils/auth";

const props = defineProps({
  modelValue: [String, Object, Array],
  limit: {
    type: Number,
    default: 5,
  },
  fileSize: {
    type: Number,
    default: 20,
  },
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg", "mp4"],
  },
  isShowTip: {
    type: Boolean,
    default: true,
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const isImagePreview = ref(true);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadMediaUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload");
const headers = ref({
  Authorization: "Bearer " + getToken(),
  "Terminal-Type": "pc",
});
const fileList = ref([]);
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));

watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        console.log("Upload Media URL:", uploadMediaUrl.value);

        const list = Array.isArray(val) ? val : props.modelValue.split(",");
        fileList.value = list.map((item) => {
          if (typeof item === "string") {
            item = { name: item, url: item };
          }
          return item;
        });
      } else {
        fileList.value = [];
        return [];
      }
    },
    { deep: true, immediate: true }
);

function handleBeforeUpload(file) {
  let isMedia = false;
  const mediaTypes = ["image", "video"];

  if (props.fileType.length) {
    const fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    isMedia = props.fileType.some(type => file.type.indexOf(type) > -1 || fileExtension === type);
  } else {
    isMedia = mediaTypes.some(type => file.type.indexOf(type) > -1);
  }

  if (!isMedia) {
    proxy.$modal.msgError(`文件格式不正确，请上传${props.fileType.join("/")}格式的文件！`);
    return false;
  }

  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB！`);
      return false;
    }
  }

  proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
}

function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个！`);
}

function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    // const defaultImage = 'https://image.nanjingtouyang.com/touy/2023/11/21/fe792e54d71a4018b61247b1868062b3.png'
    uploadList.value.push({ fileUrl:res.data.url,
      name: res.data.url, url: res.data.url, type: file.type });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);
    proxy.$refs.mediaUpload.handleRemove(file);
    uploadedSuccessfully();
  }
}

function handleDelete(file) {
  const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  if (findex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(findex, 1);
    emit("update:modelValue", listToString(fileList.value));
    return false;
  }
}

function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value
        .filter((f) => f.url !== undefined)
        .concat(uploadList.value);
    uploadList.value = [];
    console.log(fileList.value)
    number.value = 0;
    emit("update:modelValue", listToString(fileList.value));
    proxy.$modal.closeLoading();
  }
}

function handleUploadError() {
  proxy.$modal.msgError("上传文件失败");
  proxy.$modal.closeLoading();
}

function handleMediaCardPreview(file) {
  dialogImageUrl.value = file.url;
  isImagePreview.value = isImageFile(file.url);
  dialogVisible.value = true;
}

// 判断文件是否为图像类型
function isImageFile(url) {
  const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp"]; // 添加你需要支持的图像类型的扩展名
  const extension = getFileExtension(url);
  return imageExtensions.includes(extension.toLowerCase());
}

// 获取文件的扩展名
function getFileExtension(url) {
  return url.split(".").pop();
}

function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url.replace(baseUrl, "") + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return "";
  }
}
</script>

<style scoped lang="scss">
:deep(.hide .el-upload--picture-card) {
  display: none;
}
.component-upload-media {
  /* Add your specific styles for the component wrapper here */
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
